package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @PostMapping("reg")
    public int  reg(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO"+userRegDTO);
        String username=userRegDTO.getUsername();
        UserVO userVO=userMapper.selectByUsername(username);
        log.debug("userVO"+userVO);
        if(userVO!=null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        log.debug("user"+user);
        userMapper.insertUser(user);

        return 1;
    }
    @ApiOperation("登录功能")
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession  session){
        log.debug("userLoginDTO"+userLoginDTO);
        String username=userLoginDTO.getUsername();
        UserVO userVO=userMapper.selectByUsername(username);
        if(userVO!=null){
            String password=userLoginDTO.getPassword();
            if(userVO.getPassword().equals(password)){
                session.setAttribute("user",userVO);
                return 1;
            }else{
                return 2;
            }
        }else {
            return 3;
        }
    }
    @ApiOperation("获取当前用户信息")
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO=(UserVO) session.getAttribute("user");
        return userVO;
    }
    @ApiOperation("退出登录功能")
    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
